package com.atguigu.spring.tx.dao.impl;

import com.atguigu.spring.tx.bean.Book;
import com.atguigu.spring.tx.dao.BookDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class BookDAOImpl implements BookDAO {
    @Autowired
    JdbcTemplate template;

    @Override
    public Book getBookById(int id) {
        String sql = "select * from book where `id` = ?";
        return template.queryForObject(sql, new BeanPropertyRowMapper<>(Book.class), id);
    }

    @Override
    public int addBook(Book book) {
        String sql = "insert into book(bookName, price, stock) values(?,?,?)";
        int updated = template.update(sql, book.getBookName(), book.getPrice(), book.getStock());
        return updated;
    }

    @Override
    public int customStock(int id, int count) {
        Book book = getBookById(id);
        if (book.getStock() > count) {
            String sql = "update book set stock = stock - ? where id = ?";
            int updated = template.update(sql, count, id);
            if (updated > 0) {
                 return getBookById(id).getStock();
            }
        }
        deleteBook(id);
        return 0;
    }

    @Override
    public int deleteBook(int id) {
        String sql = "delete from book where id = ?";
        int updated = template.update(sql, id);
        return updated;
    }
}
